package cn.ym.mall.dao.impl;

import cn.ym.mall.dao.AnnouncementDao;
import cn.ym.mall.entity.Announcement;
import cn.ym.mall.utils.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * 赵金明
 * 2022/8/11
 */
public class AnnouncementDaoImpl implements AnnouncementDao {
    QueryRunner queryRunner = new QueryRunner();

    /**
     * 新增公告
     * @param announcement 添加的公告
     * @return 新增的条数
     */
    @Override
    public Integer addAnnouncement(Announcement announcement)throws SQLException  {
        String sql = "insert into ym_announcement(aceid,acename,acecotent) values (?,?,?);";
        Object[] params = new Object[]{announcement.getAceid(),announcement.getAcenamed(),announcement.getAcecontent() };
        return queryRunner.update(DruidUtils.getConnection(), sql, params);
    }

    /**
     * 删除公告
     * @param aceid
     * @return
     */
    @Override
    public Integer deleteByAceid(Integer aceid) throws SQLException {
        int num = 0;
        String sql = "delete from ym_announcement where aceid = ?;";
        num = queryRunner.update(DruidUtils.getConnection(), sql, aceid);
        return num;
    }

    /**
     * 通过公告id查询公告
     * @param aceid
     * @return
     * @throws SQLException
     */
    @Override
    public Announcement getAnnouncementByAceid(Integer aceid) throws SQLException{
        String sql = "select * from ym_announcement where aceid = ?;";
        return queryRunner.query(DruidUtils.getConnection(), sql, new BeanHandler<Announcement>(Announcement.class), aceid);
    }

    /**
     * 查询公告总数
     *
     * @return
     */
    @Override
    public long getAnnouncementCount() throws SQLException {
        long count = 0;
        try {
            String sql = "select count(0) as count from ym_announcement;";
            count = queryRunner.query(DruidUtils.getConnection(), sql, new ScalarHandler<>());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return count;
    }

    /**
     * 分页查询公告
     * @param pageNo
     * @param pageSize
     * @return
     * @throws SQLException
     */
    @Override
    public List<Announcement> getPageAnnouncement( Integer pageNo, Integer pageSize) throws SQLException {
        String sql = "select * from ym_announcement order by aceid desc limit ?,?;";
        List<Announcement> announcementList = null;
        try {
            announcementList = queryRunner.query(DruidUtils.getConnection(), sql, new BeanListHandler<Announcement>(Announcement.class), (pageNo - 1) * pageSize, pageSize);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return announcementList;
    }

}
